<?
if($argc != 2) die('Ingrese nombre de archivo de texto como parametro.');
$filename = $argv[1];

$dicc = Array();

//$filename = "./pepe.txt";
$buffer_size = 1024 * 5;

$file = fopen($filename,'r');

$cont = 0;
$cont_2 = 0;
$i=61; while($i-->0) echo " "; echo "]\r[";


while( $buffer = fgets($file,$buffer_size) ){

	for( $i=0; $i<strlen($buffer) ; $i++ ){
		$char = $buffer[$i];
		$ord  = ord($char);
		
		if( isset($dicc[$ord]) ){
			$dicc[$ord]++;
		}else{
			$dicc[$ord] = 1;
		}

	}

	if( $cont++ % 500 == 0 ){
		echo "."; $cont_2++;
	}
	if($cont_2 > 59){
		$cont_2 = 0; $i=60; echo "]\r["; while($i-->0) echo " "; echo "]\r[";
	}
}

fclose($file);
echo PHP_EOL;

// Ordeno el array
arsort($dicc,SORT_NUMERIC);

echo "dec,hexa,char,freq\n";
//for($i=0 ; $i<256 ; $i++ ){
foreach($dicc as $i => $val){
	
	$chr = chr($i);
	$ok = false;
	if($chr == "\n"){
		$ok = true;
		$chr = '\n';
	}elseif($chr == "\r"){
		$ok = true;
		$chr = '\r';
	}elseif($chr == "\t"){
		$ok = true;
		$chr = '\t';
	}elseif($chr == ' '){
		$ok = true;
		$chr = 'BLANK';
	}
	if( $ok or preg_match( "%^[\w:?!\$=\%/\{\}\)\(\\'-]$%" , $chr )  ){
		printf("%d,%02X,%s,%d\n",$i,$i,$chr,$val);
	}else{
		printf("%d,%02X,,%d\n",$i,$i,$val);
	}
	
}

$used_chars = Array();
echo "\n\n\nPython code:\n\n";
echo "lista = []\n";
foreach($dicc as $i => $val){
	$used_chars[]=$i;
	echo "lista.append($i)\n";
}
for($i=0;$i<256;$i++){
	if( in_array($i,$used_chars) ) continue;
	echo "lista.append($i)\n";
}

?>
